package com.acerola.mrpc;

import com.acerola.mrpc.handler.RpcClientHandler;
import com.acerola.mrpc.message.RpcProtocol;
import com.acerola.mrpc.message.RpcRequest;
import com.acerola.mrpc.protocol.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: mrpc
 * @description: 客户端
 * @author: Acerola
 * @create: 2022-12-10 18:43
 **/
@Slf4j
public class Client {
    private String serverAddress;
    private int serverPort;
    private Bootstrap bootstrap;
    private NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();

    public Client(String serverAddress, int serverPort) {
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("开始初始化客户端");
                        ch.pipeline().addLast(new ProcotolFrameDecoder());
                        ch.pipeline().addLast(new LoggingHandler());
//                        ch.pipeline().addLast(new MessageCodecSharable());
                        ch.pipeline().addLast(new MessageEncode());
                        ch.pipeline().addLast(new MessageDecode());
                        ch.pipeline().addLast(new RpcClientHandler());
                    }
                });
    }

    public void startClient(RpcProtocol<RpcRequest> rpcProtocol) throws InterruptedException {
        final ChannelFuture future = bootstrap.connect(serverAddress, serverPort).sync();
        //监听是否连接成功
        future.addListener(listener -> {
            if (future.isSuccess()) {
                log.debug("connect rpc server {} success.", serverAddress);
            } else {
                log.debug("connect rpc server {} failed. ", serverAddress);
                eventLoopGroup.shutdownGracefully();
            }
        });
        System.out.println("begin transfer data");
        future.channel().writeAndFlush(rpcProtocol)
                .addListener(promise -> {
                    if (!promise.isSuccess()) {
                        Throwable cause = promise.cause();
                        log.error("error", cause);
                    }
                });
    }
}
